﻿package com.luck.pf.framework.action;

import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.DefaultActionSupport;

import com.luck.org.entity.SysLog;
import com.luck.pf.common.Constants;
import com.luck.pf.common.entity.UserBean;
import com.luck.pf.exception.ParameterException;
import com.luck.pf.exception.SessionLostException;
import com.luck.pf.util.DateUtil;


public abstract class BaseActionSupport extends DefaultActionSupport {
	private static final long serialVersionUID = 8286327415348311397L;

	public static Logger logger = Logger.getLogger(BaseActionSupport.class);
	
	public final static Long ADD_PK = Long.valueOf(-1);
	protected String msgStr="您的操作已成功!";
	
	//返回的json数据信息
	protected String jsonString;
	
	/**
	 * 全局转向
	 */
	protected static String GLOBAL_SUCCESS = "global_success";
	protected static String GLOBAL_ERROR = "global_error";
	protected static String GLOBAL_ALERT_CLOSE = "global_alert_close";
	/**
	 * 转向地址
	 */
	protected String redirectUrl;
	/**
	 * 标题
	 */
	protected String title;
	/**
	 * 用户操作类型
	 */
	protected String event;
	/**
	 * 查询序列化值
	 */
	protected String qryHex;

	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	
	protected Cookie[] getCookies(){
		return ServletActionContext.getRequest().getCookies();
	}
	protected HttpSession getSession(){
		return ServletActionContext.getRequest().getSession();
	}

    /**
     *获取session中的用户信息对象
     */
    protected UserBean getUserInfo() throws SessionLostException {
    	UserBean userInfo = (UserBean) this.getSession().getAttribute(Constants.SESSION_USER_BEAN);
		if (userInfo == null) {
			throw new SessionLostException();
		} else {
			return userInfo;
		}
	}
    /**
     * 创建日志对象实体,1：登陆日志，2:系统日志，3,业务日志
     * @return
     */
    protected SysLog createLog(UserBean userBean, String remark, String logType){
    	SysLog log = new SysLog();
    	log.setLogType(logType);
    	log.setOperTime(DateUtil.getDate());
    	log.setOperUser(userBean.getUser().getRealname()+"["+userBean.getLoginName()+"]");
    	log.setRemark(remark);
    	return log;
    }
	/**
     * 取得整型参数的值
     */
    protected int getIntParameter(String parameter){
    	Object value = getRequest().getParameter(parameter);
    	if(value!=null){
    		try{
    			return Integer.parseInt(((String[])value)[0]);
    		}
    		catch(Exception e){
    			return 0;
    		}
    	}
 		return 0;    	
    }
    
    /**
     * 取得request中parameter的值
     */
    protected String[] getParameterValues(String parameter) {
    	String[] values = this.getRequest().getParameterValues(parameter);
    	if(values!=null){
    		return values;
    	}
    	return new String[]{};
    }

    
    /**
	 * 从request中获取String类型
	 */
	public String getStringParameter(String parameter, boolean isNull) throws ParameterException {
		String value = this.getRequest().getParameter(parameter);
		if (StringUtils.isBlank(value)) {
			if (!isNull) {
				throw new ParameterException(parameter + " 参数不能为空");
			} else {
				return "";
			}
		} else {
			return value;
		}
	}
    
	/**
	 * 获取Long类型
	 */
	protected Long getLongParameter(String parameter, boolean isNull) throws ParameterException {
		String value = this.getRequest().getParameter(parameter);
		if (StringUtils.isBlank(value)) {
			if (!isNull) {
				throw new ParameterException(parameter + " 参数不能为空");
			} else {
				return null;
			}
		} else {
			return Long.parseLong(value);
		}
	}
	
	/**
	 * 获取double类型
	 */
	protected Double getDoubleParameter(String parameter, boolean isNull) throws ParameterException {
		String value = this.getRequest().getParameter(parameter);
		if (StringUtils.isBlank(value)) {
			if (!isNull) {
				throw new ParameterException(parameter + " 参数不能为空");
			} else {
				return null;
			}
		} else {
			return Double.parseDouble(value);
		}
	}
    
	/**
	 * 拷贝非空属性

	 * 
	 * @param dest
	 * @param orig
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	protected void copyProperties(Object dest, Object orig)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		if (dest == null) {
			throw new IllegalArgumentException("No destination bean specified");
		}
		if (orig == null) {
			throw new IllegalArgumentException("No origin bean specified");
		}
		PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig);
		for (int i = 0; i < origDescriptors.length; i++) {
			String name = origDescriptors[i].getName();
			
			if (PropertyUtils.isReadable(orig, name)) {
				if (PropertyUtils.isWriteable(dest, name)) {
					Object value = PropertyUtils.getSimpleProperty(orig, name);
					if (value != null) {
						PropertyUtils.setSimpleProperty(dest, name, value);
					}
				}
			}
		}
	}
    
	/**
	 * 直接输出.
	 * @param contentType
	 * 内容的类型.html,text,xml的值见后，json为"text/x-json;charset=UTF-8"
	 */
	private void render(HttpServletResponse response, String text,String contentType) {
		try {
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {
		}
	}

	/**
	 * 写内容到输入页面
	 * 
	 * @param response
	 * @param content
	 * @throws IOException
	 */
	protected void rendText(HttpServletResponse response, String content) {
		render(response, content, "text/plain;charset=UTF-8");
	}
	
	protected void rendText(String content) {
		render(getResponse(),content,"text/plain;charset=UTF-8");		
	}
	
	/**
	 * 直接输出纯HTML.
	 */
	protected void renderHtml(String text) {
		render(getResponse(), text, "text/html;charset=UTF-8");
	}

	/**
	 * 直接输出纯XML.
	 */
	protected void renderXML(String text) {
		render(getResponse(), text, "text/xml;charset=UTF-8");
	}
	
	/**
	 * 返回JSON成功信息
	 * @param message
	 */
	protected void renderJsonSuccess(String message){
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("status", SUCCESS);
		jsonMap.put("message", message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		this.rendText(jsonObject.toString());
	}
	
	/**
	 * 返回JSON成功信息
	 * @param message
	 */
	protected void renderJsonError(String message){
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("status", ERROR);
		jsonMap.put("message", message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		this.rendText(jsonObject.toString());
	}
	/**
	 * 将堆栈信息打印出来
	 * @param e
	 * @return
	 */
	protected String makeStackTraceString(Exception e){
		ByteArrayOutputStream buf = new ByteArrayOutputStream(); 
		PrintWriter pw = new PrintWriter(buf,true);
	    e.printStackTrace(pw);
	    String expMessage = buf.toString();
	    pw.close();
	    return expMessage;
	}
	protected void addAttribute(String name,String value){
		this.getRequest().setAttribute("param_"+name, value);
	}
	public String getMsgStr() {
		return msgStr;
	}

	public void setMsgStr(String msgStr) {
		this.msgStr = msgStr;
	}

	public String getJsonString() {
		return jsonString;
	}

	public void setJsonString(String jsonString) {
		this.jsonString = jsonString;
	}

	public String getRedirectUrl() {
		return redirectUrl;
	}

	public void setRedirectUrl(String redirectUrl) {
		this.redirectUrl = redirectUrl;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getEvent() {
		return event;
	}

	public void setEvent(String event) {
		this.event = event;
	}

	public String getQryHex() {
		return qryHex;
	}

	public void setQryHex(String qryHex) {
		this.qryHex = qryHex;
	}

}
